package com.apes.framework.util.monitor.druid.sql;

import com.alibaba.druid.stat.JdbcSqlStatValue;
import com.apes.framework.config.redis.RedisMessageListener;
import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.util.monitor.AbstractMonitorService;
import com.apes.framework.util.monitor.Constants;
import com.apes.framework.util.monitor.MonitorUtil;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

@Service
public class SqlStatService extends AbstractMonitorService<JdbcSqlStatValue> {
    private SqlStatRepository statRepository;
    private SqlStatValueRepository repository;

    public SqlStatService(DataSource dataSource, SqlStatValueRepository repository, SqlStatRepository statRepository, Cache cache) {
        super(cache, dataSource);
        this.repository = repository;
        this.statRepository = statRepository;
    }

    @Override
    public void run(JdbcSqlStatValue statValue) {
        String id = String.valueOf(statValue.getSqlHash());
        SqlStatValue sqlStatValue = repository.findById(id).orElse(new SqlStatValue(id));
        MonitorUtil.copyAll(statValue, sqlStatValue, "id");
        repository.save(sqlStatValue);
        statRepository.save(sqlStatValue.getSqlStat());
    }

    @Override
    public String getTopic() {
        return Constants.CONST_DRUID_SQL_ENABLE;
    }

    @Override
    protected void deleteAllData() {
        repository.deleteAll();
        statRepository.deleteAll();
    }

}
